/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hanhishi.client.presenter;

import br.com.sales.generics.client.HanAbstractPresenter;
import br.com.sales.generics.client.components.HAccordion;
import br.com.sales.generics.client.components.scroll.HScroll;
import br.com.sales.generics.client.components.timepicker.HDateTimePicker;
import br.com.sales.generics.client.nametoken.NameTokens;
import br.com.sales.generics.client.request.HannaRequestCallback;
import br.com.sales.generics.client.utils.User;
import br.com.sales.hanhishi.client.service.HanHisHIService;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author v
 */
public class HanHisHIPresenter
        extends HanAbstractPresenter<HanHisHIPresenter.Display, HanHisHIPresenter.MyProxy>
        implements HanHisHIUiHanlder {

    @Inject
    private HanHisHIService service;
    @Inject
    private Provider<User> user;
    private final HTMLPanel viewReportPanel = new HTMLPanel("");
    private JSONArray jSONArray;
    private final Button impressBtn = new Button("Imprimir");
    private final PopupPanel popup = new PopupPanel(true);

    @Inject
    public HanHisHIPresenter(EventBus eventBus, Display view, MyProxy proxy) {
        super(eventBus, view, proxy);
        getView().setUiHandlers(this);
    }

    @Override
    protected void onReveal() {
        super.onReveal();
        update();
    }

    private Map getDataFilter() {
        LinkedHashMap parHash = new LinkedHashMap();
        parHash.put("IE_FILTRAR", getView().getIeFiltrarData().getValue() ? "S" : "N");
        parHash.put("START", getView().getInitialDate().getValueAsString() + " 00:00:00");
        parHash.put("FINISH", getView().getFinalDate().getValueAsString() + " 23:59:59");
        parHash.put("NM_CLIENTE", getView().getFilterName().getValue());

        return parHash;
    }

    private Object ifNull(JSONValue value) {
        if (value == null) {
            return "";
        } else if (value instanceof JSONString) {
            return value.isString().stringValue();
        } else if (value instanceof JSONNumber) {
            return Long.parseLong(value.isNumber().toString());
        } else {
            return JSONNull.getInstance();
        }
    }

    private void update() {
        getView().getLayout().clear();
        service.getData(getDataFilter(), new HannaRequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                HAccordion accordion = new HAccordion();
                JSONArray json = new JSONArray(JsonUtils.safeEval(response.getText()));
                jSONArray = json;
                HorizontalPanel salesPanel;
                VerticalPanel itemsPanel;

                for (int index = 0; index < json.size(); index++) {
                    salesPanel = new HorizontalPanel();
                    itemsPanel = new VerticalPanel();
                    JSONObject sales = json.get(index).isObject().get("SALES").isObject();
                    HTMLPanel panel = new HTMLPanel("Data: " + ifNull(sales.get("DT_VENDA")));
                    panel.addStyleName("data-venda");
                    salesPanel.add(panel);
                    panel = new HTMLPanel("Cliente: " + ifNull(sales.get("CLIENT")));
                    panel.addStyleName("cliente-venda");
                    salesPanel.add(panel);
                    panel = new HTMLPanel("Total venda: " + ifNull(sales.get("VL_TOTAL_VENDA")));
                    panel.addStyleName("total-venda");
                    salesPanel.add(panel);

                    JSONArray items = json.get(index).isObject().get("ITEMS").isArray();
                    if (items != null) {
                        for (int itemIndex = 0; itemIndex < items.size(); itemIndex++) {
                            HorizontalPanel itemsSubPanel = new HorizontalPanel();
                            panel = new HTMLPanel("Produto: " + ifNull(items.get(itemIndex).isObject().get("DS")));
                            panel.addStyleName("ds-venda");
                            itemsSubPanel.add(panel);
                            panel = new HTMLPanel("Quantidade: " + ifNull(items.get(itemIndex).isObject().get("QT")));
                            panel.addStyleName("qt-venda");
                            itemsSubPanel.add(panel);
                            panel = new HTMLPanel("Valor: " + ifNull(items.get(itemIndex).isObject().get("VL")));
                            panel.addStyleName("vl-venda");
                            itemsSubPanel.add(panel);
                            itemsPanel.add(itemsSubPanel.asWidget());
                        }
                    }
                    accordion.addContent(salesPanel.asWidget(), itemsPanel.asWidget());
                }
                adjustReport();
                getView().getLayout().add(accordion);
            }
        });
    }

    private void adjustReport() {
        double totalPrice = 0D;
        int count = 0;
        viewReportPanel.clear();
        HorizontalPanel salesPanel;
        VerticalPanel itemsPanel;
        String provider = getView().getFilterName().getText();
        String headerText = "<h3><b>De</b> " + getView().getInitialDate().getValueAsString()
                + " <b>até</b> " + getView().getFinalDate().getValueAsString() + "</h3>";
        if (!"".equals(provider)) {
            headerText = "<br><h3><b>Fornecedor:</b> " + provider + "</h3>";
        }
        HTML header = new InlineHTML(headerText);
        header.setStyleName("header-report", true);
        viewReportPanel.add(new HTML("<h1>Registros de vendas</h1>"));
        viewReportPanel.add(header);

        for (int index = 0; index < jSONArray.size(); index++) {
            salesPanel = new HorizontalPanel();
            salesPanel.setStyleName("content-report", true);
            itemsPanel = new VerticalPanel();
            JSONObject sales = jSONArray.get(index).isObject().get("SALES").isObject();
            HTMLPanel panel = new HTMLPanel("Data: " + ifNull(sales.get("DT_VENDA")));
            panel.addStyleName("data-venda");
            salesPanel.add(panel);
            panel = new HTMLPanel("Cliente: " + ifNull(sales.get("CLIENT")));
            panel.addStyleName("cliente-venda");
            salesPanel.add(panel);
            Double totalSales = Double.parseDouble(((String) ifNull(sales.get("VL_TOTAL_VENDA"))).replaceAll(",", ""));
            totalPrice += totalSales;
            panel = new HTMLPanel("Total venda: " + ifNull(sales.get("VL_TOTAL_VENDA")));
            panel.addStyleName("total-venda");
            salesPanel.add(panel);

            JSONArray items = jSONArray.get(index).isObject().get("ITEMS").isArray();
            if (items != null) {
                for (int itemIndex = 0; itemIndex < items.size(); itemIndex++) {
                    HorizontalPanel itemsSubPanel = new HorizontalPanel();
                    panel = new HTMLPanel("Produto: " + ifNull(items.get(itemIndex).isObject().get("DS")));
                    panel.addStyleName("ds-venda");
                    itemsSubPanel.add(panel);
                    Long countProdut = (Long) ifNull(items.get(itemIndex).isObject().get("QT"));
                    count += countProdut;
                    panel = new HTMLPanel("Quantidade: " + countProdut);
                    panel.addStyleName("qt-venda");
                    itemsSubPanel.add(panel);
                    panel = new HTMLPanel("Valor: " + ifNull(items.get(itemIndex).isObject().get("VL")));
                    panel.addStyleName("vl-venda");
                    itemsSubPanel.add(panel);
                    itemsPanel.add(itemsSubPanel.asWidget());
                }
            }
            viewReportPanel.add(salesPanel.asWidget());
            viewReportPanel.add(itemsPanel.asWidget());
        }
        HTML footer = new InlineHTML("<hr><b>Total vendas:</b> R$ " + totalPrice
                + "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp    <b>Total de produtos:</b> "
                + count + "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp    <b>Usuário:</b> " + user.get().getNmUser());
        footer.setStyleName("footer-report", true);
        viewReportPanel.add(footer);
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().getLayout().addStyleName("container-historic");
        getView().build();
        impressBtn.setStyleName("impress-btn", true);
        viewReportPanel.getElement().setId("section-to-print");
        impressBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                print();
                popup.hide();
            }
        });
    }

    private native void print() /*-{
     function printReport(){
     var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
     var docprint= $wnd.open("about:blank", "_blank",strWindowFeatures); 
     var myReport = $doc.getElementById("section-to-print");
     docprint.document.open(); 
     docprint.document.write('<html><head><title>Relatório</title>'); 
     docprint.document.write('<link rel="stylesheet" href="http://chapolinekarine.com.br/HannaSys/css/hanhishi/hanhishi.css" type="text/css">'); 
     docprint.document.write('</head><body>');
     docprint.document.write(myReport.innerHTML);
     docprint.document.write('</body></html>'); 
     docprint.document.close();
     docprint.print();
     docprint.close();
     }
     printReport();
     }-*/;

    @Override
    public void onClickRefresh(ClickEvent event) {
        update();
    }

    @Override
    public void onClickViewReport(ClickEvent event) {
        HScroll scroll = new HScroll();
        scroll.addStyleName("scroll-content");
        scroll.add(impressBtn);
        scroll.add(viewReportPanel);
        popup.clear();
        popup.add(scroll);
        popup.setGlassEnabled(true);
        popup.setAnimationEnabled(true);
        popup.center();
        popup.show();
    }

    @ProxyStandard
    @NameToken(NameTokens.HISTORY)
    public interface MyProxy extends ProxyPlace<HanHisHIPresenter> {

    }

    public interface Display extends View, HasUiHandlers<HanHisHIUiHanlder> {

        FlowPanel getLayout();

        void build();

        HDateTimePicker getInitialDate();

        HDateTimePicker getFinalDate();

        CheckBox getIeFiltrarData();

        TextBox getFilterName();

        HTMLPanel getContainer();

    }
}
